package com.ebrothers.isns.data;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.ebrothers.isns.common.Constants;
import com.ebrothers.isns.vo.Answer;
import com.ebrothers.isns.vo.Question;

public class JsonParser {
	private static final String TAG = "JsonParser";

	public static ArrayList<Question> parseQuestions(String json) {
		ArrayList<Question> qs = new ArrayList<Question>();
		if (json != null) {
			try {
				JSONArray array = new JSONArray(json);
				int size = array.length();
				Question q;
				for (int i = 0; i < size; i++) {
					q = new Question();
					q.fromJson(array.getJSONObject(i));
					qs.add(q);
				}
			} catch (JSONException e) {
				Log.e(TAG, "****** Got an error when parse questions.", e);
			}
		}
		return qs;
	}

	public static ArrayList<Answer> parseAnswers(String json) {
		ArrayList<Answer> as = new ArrayList<Answer>();
		if (json != null) {
			try {
				JSONArray array = new JSONArray(json);
				int size = array.length();
				Answer a;
				for (int i = 0; i < size; i++) {
					a = new Answer();
					a.fromJson(array.getJSONObject(i));
					as.add(a);
				}
			} catch (JSONException e) {
				Log.e(TAG, "****** Got an error when parse answers.", e);
			}
		}
		return as;
	}

	public static String parseAddressInfo(String json) {
		if (Constants.LOGD) {
			Log.d(TAG, "****** parseAddressInfo. json=" + json);
		}
		try {
			JSONObject obj = new JSONObject(json);
			String status = obj.getString("status");
			if ("OK".equals(status)) {
				JSONArray results = obj.getJSONArray("results");
				JSONObject result = results.getJSONObject(0);
				String address = result.getString("formatted_address");
				address = address.substring(0, address.indexOf(" "));
				return address;
			}
		} catch (JSONException e) {
			Log.e(TAG, "******* Got an error when parse address name.", e);
		}
		return "";
	}
}
